import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessageBox, ElMessage } from "element-plus";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/serviceLoading";
import { getToken } from "@/utils/cookies";
import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";
import { useUserStore } from "@/stores/module/userInfo";

// HTTP 状态码映射
const HTTP_CODE_MESSAGES: Record<number, string> = {
  400: "请求失败",
  401: "未授权，请重新登录",
  403: "拒绝访问",
  404: "请求功能不存在",
  405: "请求方法未允许",
  408: "请求超时",
  500: "服务器内部错误",
  501: "网络未实现",
  502: "网络错误",
  503: "服务不可用",
  504: "网络超时",
  505: "HTTP版本不支持",
};

// 定义后端响应结构
export interface ApiResult<T = any> {
  Code: number;
  Msg: string;
  Data?: T;
}

// 环境变量配置
const BASE_URL = import.meta.env.VITE_API_URL??"https://localhost:7140/api";

// 环境检查（开发环境提供详细提示）
if (!BASE_URL && import.meta.env.DEV) {
  console.error(
    "⚠️ 环境变量 VITE_API_URL 未配置！\n\n" +
    "请创建环境配置文件并添加：\n" +
    "VITE_API_URL = 'https://your-api-url/api'\n\n" +
    "可用环境文件：\n" +
    "  .env.dev      - 开发环境\n" +
    "  .env.sit      - 测试环境\n" +
    "  .env.uat      - 预发布环境\n" +
    "  .env.prod     - 生产环境\n\n" +
    "当前运行环境: " + import.meta.env.MODE
  );
  
  const defaultDevUrl = "https://localhost:7140/api";
  console.warn(`使用开发默认值: ${defaultDevUrl}`);
}

export default function request<T = any>(config: AxiosRequestConfig): Promise<ApiResult<T>> {
  // 创建 axios 实例
  const service = axios.create({
    baseURL: BASE_URL,
    timeout: 300 * 1000,
    withCredentials: true,
  });

  // 请求拦截器
  service.interceptors.request.use(
    (config: any) => {
      config.noLoading || showFullScreenLoading();
      
      // 设置认证头
      const token = getToken();
      if (token) {
        config.headers = config.headers || {};
        config.headers.Authorization = token;
      }

      // 动态设置 Content-Type
      if (config.type === "file") {
        config.headers = config.headers || {};
        config.headers["Content-Type"] = "multipart/form-data";
      } else if (config.type === "form") {
        config.headers = config.headers || {};
        config.headers["Content-Type"] = "application/x-www-form-urlencoded";
      } else {
        config.headers = config.headers || {};
        config.headers["Content-Type"] = config.headers["Content-Type"] || "application/json";
      }

      // 处理 GET 请求
      if (config.method?.toLowerCase() === "get") {
        config.params = config.data || config.params;
      }

      return config;
    },
    (error: any) => {
      tryHideFullScreenLoading();
      return Promise.reject(error);
    }
  );


  // 响应拦截器
  service.interceptors.response.use(
    (response: AxiosResponse<ApiResult<T>>): AxiosResponse<ApiResult<T>> => {
      tryHideFullScreenLoading();
      const apiResult = response.data;
      const code = apiResult.Code;
      const message = apiResult.Msg || "未知错误";

      if (code === 401) {
        handleUnauthorized();
        return Promise.reject(new Error("登录状态已过期")) as any;
      } 
      // 成功状态码（200 表示成功）
      if (code === 200) {
        return response;
      } 
      
      // 业务错误处理
      ElMessage({
        message: message,
        type: "error",
        duration: 5 * 1000
      });
      return Promise.reject(apiResult) as any;
    },
    (error: any) => {
      tryHideFullScreenLoading();
      
      let errorMessage = "请求失败";
      
      if (error.response) {
        const status = error.response.status;
        errorMessage = HTTP_CODE_MESSAGES[status] || `服务器错误 (${status})`;
        
        if (status === 403 && import.meta.env.PROD) {
          redirectToLogin();
          return Promise.reject(new Error("无访问权限")) as any;
        }
      } else if (error.request) {
        errorMessage = "服务器响应超时，请刷新重试";
      } else {
        errorMessage = `请求配置错误: ${error.message}`;
      }
      
      ElMessage({
        message: errorMessage,
        type: "error",
        duration: 5 * 1000
      });
      
      return Promise.reject(error);
    }
  );

  return service(config).then((res) => res.data);

}

// 处理未授权 (401)
function handleUnauthorized() {
  ElMessageBox.confirm("登录状态已过期，请重新登录", "系统提示", {
    confirmButtonText: "重新登录",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    await useUserStore().LogOut();
    redirectToLogin();
  }).catch(() => {
    // 用户点击取消，不做操作
  });
}

// 智能重定向
function redirectToLogin() {
  let loginUrl = "/login";
  
  if (typeof window !== "undefined") {
    const { protocol, hostname } = window.location;
    
    if (import.meta.env.PROD) {
      loginUrl = `${protocol}//${hostname}${loginUrl}`;
    }
    
    if (qiankunWindow.__POWERED_BY_QIANKUN__) {
      loginUrl = "/qiankun" + loginUrl;
    }
  }
  
  window.top?.location?.assign(loginUrl);
}